package com.ruoyi.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.Schedule;
import com.ruoyi.system.domain.bo.AssessmentBo;
import com.ruoyi.system.domain.bo.AttendanceBo;
import com.ruoyi.system.domain.bo.PoliceOfficerBo;
import com.ruoyi.system.domain.bo.ShiftBo;
import com.ruoyi.system.domain.vo.AssessmentVo;
import com.ruoyi.system.domain.vo.AttendanceVo;
import com.ruoyi.system.domain.vo.PoliceOfficerVo;
import com.ruoyi.system.domain.vo.ShiftVo;
import com.ruoyi.system.service.*;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaxiaya
 * @date 2025/6/24 7:51
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GenerateAIJob {


    private final IScheduleService scheduleService;

    private final DeepSeekService deepSeekService;

    private final IShiftService shiftService;

    private final IAttendanceService attendanceService;

    private final IAssessmentService assessmentService;
    private final IPoliceOfficerService policeOfficerService;

    private final ISysUserService sysUserService;

    @XxlJob("generateScheduleByAI")
    public void generateScheduleByAI() {
        XxlJobHelper.log("开始执行ai智能排班任务！");
        log.info("开始生成AI");

        // 执行智能排班算法
        PoliceOfficerBo policeOfficerBo = new PoliceOfficerBo();
        List<PoliceOfficerVo> officers = policeOfficerService.queryList(policeOfficerBo);
        for (PoliceOfficerVo sysUser : officers) {
            ShiftBo shiftBo = new ShiftBo();
            shiftBo.setUnit(sysUser.getDepartment());
            List<ShiftVo> shiftVoList = shiftService.queryList(shiftBo);

            AttendanceBo attendanceBo = new AttendanceBo();
            attendanceBo.setScheduledOfficerId(sysUser.getId());
            List<AttendanceVo> attendanceVoList = attendanceService.queryList(attendanceBo);

            AssessmentBo assessmentBo = new AssessmentBo();
            assessmentBo.setOfficerId(sysUser.getId());
            List<AssessmentVo> assessmentList = assessmentService.queryList(assessmentBo);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String shiftJson = mapper.writeValueAsString(shiftVoList);
                String attendanceJson = mapper.writeValueAsString(attendanceVoList);
                String assessmentJson = mapper.writeValueAsString(assessmentList);

                String result = deepSeekService.askAI("生成排班计划，" +
                    shiftJson + "，" + attendanceJson + "，" + assessmentJson);

                JSONObject resultJsonObject =new JSONObject(result);
                JSONObject choices =(JSONObject) resultJsonObject.getJSONArray("choices").get(0);
                String content = choices.getJSONObject("message").getStr("content");
                System.out.println(content);

                JSONArray scheduleList = null;
                List<Schedule> list = new ArrayList<>();

                try {
                    scheduleList = new JSONArray(extractJsonArray(content));
                    JSONArray aiScheduleList = ((JSONObject) scheduleList.get(0)).getJSONArray("schedule");
                    for (Object o : aiScheduleList) {
                        JSONObject jsonObject = (JSONObject) o;

                        Schedule schedule = new Schedule();
                        schedule.setOfficerId(sysUser.getId());
                        schedule.setOfficerName(sysUser.getName());
                        schedule.setOfficerType(jsonObject.getStr("dutyType"));
                        schedule.setEquipments(jsonObject.getStr("equipments"));
                        schedule.setScene(jsonObject.getStr("scene"));
                        schedule.setTimePeriod(jsonObject.getStr("timePeriod"));
                        schedule.setRoute(jsonObject.getStr("route"));
                        schedule.setScheduleDate(jsonObject.getDate("scheduleDate"));
                        schedule.setPoints(jsonObject.getStr("points"));
                        list.add(schedule);
                    }
                } catch (JSONException e) {
                    System.out.println("JSONException: " + e.getMessage());
                    scheduleList = new JSONArray(extractJsonArray(content));
                    for (Object o : scheduleList) {
                        JSONObject jsonObject = (JSONObject) o;

                        Schedule schedule = new Schedule();
                        schedule.setOfficerId(sysUser.getId());
                        schedule.setOfficerName(sysUser.getName());
                        schedule.setOfficerType(jsonObject.getStr("dutyType"));
                        schedule.setEquipments(jsonObject.getStr("equipments"));
                        schedule.setScene(jsonObject.getStr("scene"));
                        schedule.setTimePeriod(jsonObject.getStr("timePeriod"));
                        schedule.setScheduleDate(jsonObject.getDate("scheduleDate"));
                        schedule.setRoute(jsonObject.getStr("route"));
                        schedule.setPoints(jsonObject.getStr("points"));
                        list.add(schedule);
                    }
                }

                scheduleService.batchSaveSchedule(list);
            } catch (JsonProcessingException e) {
                System.out.println("JSON解析错误");
            }
        }
    }

    public static String extractJsonArray(String rawText) {
        int startIndex = rawText.indexOf('[');
        int endIndex = rawText.lastIndexOf(']');

        if (startIndex >= 0 && endIndex > startIndex) {
            return rawText.substring(startIndex, endIndex + 1);
        } else {
            throw new IllegalArgumentException("输入中不包含合法的 JSON 数组");
        }
    }
}
